<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>柱状图</title>
    <script src="./js/d3.v3.min.js"></script>
    <style>
        svg{
            border: 1px solid #333;
        }
    </style>
    <script>
        window.onload = function () {
            // 准备数据
            var arr = [
                {name:'八戒', weight: 200},
                {name:'悟空', weight: 120},
                {name:'唐僧', weight: 140},
                {name:'沙和尚', weight: 160},
            ];

            // 创建svg
            var svg = d3.select("body").append("svg")
                            .attr("width", 600)
                            .attr("height", 400)

            // 边距
            var margin = {left: 30, top: 30, right: 30, bottom: 30};

            // 线性比例尺
            var max = d3.max(arr, (item, index) => {
                return item.weight;
            });

            console.log(max);

            var yScale = d3.scale.linear()
                            .domain([0, max])
                            .range([0, 400-margin.top])

            // 添加g标签
            var g = svg.append("g")
                        .attr("fill", "tomato")
                        .attr("transform", `translate(${margin.left} 0)`)

            // 添加rect
            g.selectAll("rect").data(arr).enter()
                    .append("rect")
                    .attr("x", (item, index) => {
                        return index*(40 + 60)
                    })
                    .attr("y", (item, index) => {
                        return 400 - yScale(item.weight)
                    })
                    .attr("width", 40)
                    .attr("height", (item, index) => {
                        return yScale(item.weight)
                    })
        }
    </script>
</head>
<body>
    
</body>
</html>